import { useReactive } from "ahooks";
import { useModel } from "umi";
import { useEffect } from "react";
import compress from "gql-compress";

const useAllMemberStructuresToTree = () => {
    const { graphqlFetch } = useModel("global");
    const { organizationInfo } = useModel("organization.info");

    const state = useReactive({
        loading: false,
        isShowTree: false,
        members: [],
        memberStructures: [],
        memberStructuresTree: {},
    });

    // 加载组织所有已认证成员信息
    const loadAllMembersStructuresToTree = async (isReload = false) => {
        state.memberStructuresTree = {};
        state.isShowTree = false;
        state.loading = true;
        let res = await graphqlFetch({
            query,
            variables: {},
        });
        state.memberStructures =
            res?.a?.nodes?.map((item, i) => {
                const { isAppr, isAudt, omLeve, omUuid, paPath, paUuid, b } = item;
                return { isAppr, isAudt, omLeve, omUuid, paPath, paUuid, ...b, id: omUuid + "-p-" + i, name: b.omName, type: "person" };
            }) || [];
        let treeData = helper.transTree(state.memberStructures, "omUuid", "paUuid");
        state.memberStructuresTree = {
            id: "root",
            name: organizationInfo.fullName,
            type: "organization",
            children: treeData,
        };
        state.loading = false;
        state.isShowTree = true;
    };

    useEffect(() => {
        organizationInfo?.uuid && loadAllMembersStructuresToTree();
    }, [organizationInfo?.uuid]);

    return { ...state, loadAllMembersStructuresToTree };
};

const query = compress(`query MyQuery {
    a: allMembersStructures {
        nodes {
            isAppr
            isAudt
            omLeve
            omUuid
            paPath
            paUuid
            b: organizationMemberByOmUuid {
                omName
                omPosi
                omRoge
                omAvta
            }
        }
    }
}`);

export default useAllMemberStructuresToTree;
